<template>
	<view class="content">
		<navbar name="数据详情"></navbar>
		<view class="HealthReport">
			<view class="titlename">
				<view class="titlename-title">
					健康报告
				</view>
				<view class="titlename-time">
					2021年10月08日
				</view>
			</view>
			<view class="heavy-flex">
				<view class="weight-view">
					体重
					<view class="weight-num">
						55.6<text>kg</text>
					</view>
				</view>
				<view class="weight-view">
					体重
					<view class="weight-num">
						55.6<text>kg</text>
					</view>
				</view>
			</view>
			<view class="reportItemList-body">
				<view class="reportItemList" v-for="(item,index) in resarr" :key="index">
					<view class="reportItemList-flex">
						<view class="reportItemList-item" v-for="(items,indexs) in item" :key="indexs"
							:style="indexs==2?'border-right: none;':''" @tap="reportItemTab(items,index,indexs)">
							<view class="view-name">
								{{items.name||''}}
							</view>
							<view class="view-unit">
								{{items.value||''}}<text>{{items.unit||''}}</text>
							</view>
							<view class="view-level" :style="'color:'+items.bar[items.level]">
								{{items.levelNames[items.level]}}
							</view>
						</view>
					</view>
					<view class="reportItemList-height" :class="[indexs==0?'prbefoer0':'',indexs ==1?'prbefoer1':'',indexs==2?'prbefoer2':'']"  v-if="index == tabIndex">
						<view class="view-levelNamesflex" v-if="showBar">
							<view class="view-levelNames" v-for="(itema,indexa) in boundaries" :key="indexa">
								{{itema}}
							</view>
						</view>
						<view class="view-progress" v-if="showBar">
							<progress :percent="reportPercent" :activeColor="bar[level+1]" active stroke-width="8" />
						</view>
						<view class="view-levelNamesflex" v-if="showBar">
							<view class="view-levelNames" v-for="(itema,indexa) in levelNames" :key="indexa">
								{{itema}}
							</view>
						</view>
						<view class="view-desc">
							{{desc}}
						</view>
					</view>
				</view>
			</view>
			<button class="shareImage" type="primary" @tap="shareFc()">点击生成图片</button>
		</view>
		<!-- 生成海报 -->
		<!-- 图片展示由自己实现 -->
		<QSPopup ref="popup">
			<view class="flex_column">
				<view class="backgroundColor-white padding1vh border_radius_10px">
					<image :src="posterImage || ''" mode="widthFix" class="posterImage"></image>
				</view>
				<view class="flex_row marginTop2vh">
					<button type="primary" size="mini" @tap.prevent.stop="saveImage()">保存图片</button>
					<button type="primary" size="mini" @tap.prevent.stop="share()">分享图片</button>
				</view>
			</view>
		</QSPopup>
		<!-- 画布 -->
		<view class="hideCanvasView">
			<canvas class="hideCanvas" id="default_PosterCanvasId" canvas-id="default_PosterCanvasId"
				:style="{width: (poster.width||10) + 'px', height: (poster.height||10) + 'px'}"></canvas>
		</view>
	</view>
</template>

<script>
	import QSPopup from './components/QS-popup/QS-popup.vue'
	import _app from './components/QuShe-SharerPoster/QS-SharePoster/app.js';
	import {
		getSharePoster
	} from './components/QuShe-SharerPoster/QS-SharePoster/QS-SharePoster.js';
	import Decoder from "./components/decoder";
	export default {
		components: {
			QSPopup,
		},
		data() {
			return {
				showBar: '',
				bar: [], //颜色
				reportPercent: 0, //报告百分比
				level: 0, //等级
				boundaries: [], //
				levelNames: [], //等级数组
				indexs: 999, //子级值
				tabIndex: 999, //点击索引
				desc: '',
				resarr: [], //转换后的数组
				report: {
					reportItemList: []
				}, //js解析完成数据
				poster: {},
				resarr: [], //转换后的数组
				posterImage: '',
				canvasId: 'default_PosterCanvasId'
			}
		},
		onLoad(e) {
			this.getHealthData(e.healthDataId)
		},
		methods: {
			// 获取百分比
			toPercent(num, total) {
				console.log((Math.round(num / total * 10000) / 100.00), '417777777777777777')
				return (Math.round(num / total * 10000) / 100.00); // 小数点后两位百分比
			},
			reportItemTab(item, index, indexs) {
				console.log(item, 175555)
				if (index == this.tabIndex && this.tabIndex != 999 && this.indexs != 999 && indexs == this.indexs) {
					index = 999
					indexs = 999
				}
				if (item.levelNames) {
					this.reportPercent = this.toPercent(item.level + 1, item.levelNames.length)
				}
				this.showBar = item.showBar
				this.boundaries = item.boundaries
				this.bar = item.bar
				this.levelNames = item.levelNames
				this.desc = item.desc
				this.indexs = indexs
				this.tabIndex = index;
			},
			GetAge(strBirthday) {
				var returnAge,
					strBirthdayArr = strBirthday.split("-"),
					birthYear = strBirthdayArr[0],
					birthMonth = strBirthdayArr[1],
					birthDay = strBirthdayArr[2],
					d = new Date(),
					nowYear = d.getFullYear(),
					nowMonth = d.getMonth() + 1,
					nowDay = d.getDate();
				if (nowYear == birthYear) {
					returnAge = 0; //同年 则为0周岁
				} else {
					var ageDiff = nowYear - birthYear; //年之差
					if (ageDiff > 0) {
						if (nowMonth == birthMonth) {
							var dayDiff = nowDay - birthDay; //日之差
							if (dayDiff < 0) {
								returnAge = ageDiff - 1;
							} else {
								returnAge = ageDiff;
							}
						} else {
							var monthDiff = nowMonth - birthMonth; //月之差
							if (monthDiff < 0) {
								returnAge = ageDiff - 1;
							} else {
								returnAge = ageDiff;
							}
						}
					} else {
						returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
					}
				}
				return returnAge; //返回周岁年龄
			},
			getScaleCompareData(healthDataId1){
				this.$api.get(global.apiUrls.getScaleCompareData, {
					healthDataId1:healthDataId1
					})
					.then(res => {
						if (res.data.code == 1000) {
						}
					}).catch(err => {})
			},
			// 获取电子秤数据
			getHealthData(healthDataId) {
				let _this = this;
				let sendData = {
					healthDataId: healthDataId
				};
				this.$api.post(global.apiUrls.getHealthData, sendData)
					.then(res => {
						if (res.data.code == 1000) {
							let scaleData = res.data.result;
							scaleData.healthData = JSON.parse(scaleData.healthData)
							let daytype = _this.$basejs.dataType(scaleData.createTime)
							scaleData.createTimeDay = daytype.n + '年' + daytype.y + '月' + daytype.r + '日'
							console.log(scaleData, '24111111111111')
							_this.scaleData = scaleData
							let dataT = scaleData.healthData
							const report = new Decoder(dataT)
							console.log(report, '2888888888888888')
							let baseArray = report.reportItemList;
							let len = baseArray.length;
							let n = 3; //假设每行显示4个
							let lineNum = len % 3 === 0 ? len / 3 : Math.floor((len / 3) + 1);
							let resarr = [];
							for (let i = 0; i < lineNum; i++) {
								// slice() 方法返回一个从开始到结束（不包括结束）选择的数组的一部分浅拷贝到一个新数组对象。且原始数组不会被修改。
								let temp = baseArray.slice(i * n, i * n + n);
								resarr.push(temp);
							}
							_this.resarr = resarr
							console.log(resarr, '252222222222');
							_this.report = report;
							console.log(report, '4900000000000000')
						}
					}).catch(err => {})
			},
			async shareFc() {
				try {
					_app.log('准备生成:' + new Date())
					const d = await getSharePoster({
						_this: this, //若在组件中使用 必传
						type: 'testShareType',
						formData: {
							//访问接口获取背景图携带自定义数据

						},
						posterCanvasId: this.canvasId, //canvasId
						delayTimeScale: 2000, //延时系数
						/* background: {
							width: 1080,
							height: 1920,
							backgroundColor: '#666'
						}, */
						drawArray: ({
							bgObj,
							type,
							bgScale
						}) => {
							const dx = bgObj.width * 0.3;
							const fontSize = bgObj.width * 0.045;
							const lineHeight = bgObj.height * 0.04;
							//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
							return new Promise((rs, rj) => {
								rs([{
										type: 'custom',
										setDraw(Context) {
											Context.setFillStyle('black');
											Context.setGlobalAlpha(0.3);
											Context.fillRect(0, bgObj.height - bgObj
												.height * 0.2, bgObj.width, bgObj
												.height * 0.2);
											Context.setGlobalAlpha(1);
										}
									},
									// {
									// 	type: 'image',
									// 	url: '/static/3.jpg',
									// 	alpha: .3,
									// 	dx,
									// 	dy: bgObj.height - bgObj.width * 0.25,
									// 	infoCallBack(imageInfo) {
									// 		let scale = bgObj.width * 0.2 / imageInfo.height;
									// 		return {
									// 			circleSet: {
									// 				x: imageInfo.width * scale / 2,
									// 				y: bgObj.width * 0.2 / 2,
									// 				r: bgObj.width * 0.2 / 2
									// 			}, // 圆形图片 , 若circleSet与roundRectSet一同设置 优先circleSet设置
									// 			dWidth: imageInfo.width * scale, // 因为设置了圆形图片 所以要乘以2
									// 			dHeight: bgObj.width * 0.2,
									// 			/* roundRectSet: { // 圆角矩形
									// 				r: imageInfo.width * .1
									// 			} */
									// 		}
									// 	}
									// },
									{
										type: 'text',
										fontStyle: 'italic',
										text: '取舍',
										size: fontSize,
										color: 'white',
										alpha: .5,
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											_app.log(
												'index页面的text的infocallback ，textlength:' +
												textLength);
											return {
												dx: bgObj.width - textLength - fontSize,
												dy: bgObj.height - lineHeight * 3
											}
										},
										serialNum: 0,
										id: 'tag1' //自定义标识
									},
									{
										type: 'text',
										text: '取舍',
										fontWeight: 'bold',
										size: fontSize,
										color: 'white',
										alpha: .75,
										textAlign: 'left',
										textBaseline: 'middle',
										serialNum: 1,
										allInfoCallback({ //v3.0.1 更新 可以获取drawArray中全部数据
											drawArray
										} = {}) {
											const obj = drawArray.find(item => item.id ===
												'tag1');
											/* return {
												dx: obj.dx,
												dy: obj.dy + lineHeight
											} */
											//也可以return promise对象
											return new Promise((rs, rj) => {
												setTimeout(() => {
													rs({
														dx: obj.dx,
														dy: obj
															.dy +
															lineHeight
													});
												}, 1);
											});
										}
									},
									{
										type: 'text',
										text: '取舍',
										size: fontSize,
										color: 'white',
										alpha: 1,
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											return {
												dx: bgObj.width - textLength - fontSize,
												dy: bgObj.height - lineHeight
											}
										}
									},
									{
										type: 'qrcode',
										text: '你好，我是取舍',
										size: bgObj.width * 0.2,
										dx: bgObj.width * 0.05,
										dy: bgObj.height - bgObj.width * 0.25
									}
								]);
							})
						},
						setCanvasWH: ({
							bgObj,
							type,
							bgScale
						}) => { // 为动态设置画布宽高的方法，
							this.poster = bgObj;
						}
					});
					_app.log('海报生成成功, 时间:' + new Date() + '， 临时路径: ' + d.poster.tempFilePath)
					this.posterImage = d.poster.tempFilePath;
					this.$refs.popup.show()
				} catch (e) {
					_app.hideLoading();
					_app.showToast(JSON.stringify(e));
					console.log(JSON.stringify(e));
				}
			},
			saveImage() {
				// #ifndef H5
				uni.saveImageToPhotosAlbum({
					filePath: this.poster.finalPath,
					success(res) {
						_app.showToast('保存成功');
					}
				})
				// #endif
				// #ifdef H5
				_app.showToast('保存了');
				// #endif
			},
			share() {
				// #ifdef APP-PLUS
				_app.getShare(false, false, 2, '', '', '', this.poster.finalPath, false, false);
				// #endif

				// #ifndef APP-PLUS
				_app.showToast('分享了');
				// #endif
			},
			hideQr() {
				this.$refs.popup.hide()
			}
		}
	}
</script>

<style lang="scss">
	.hideCanvasView {
		position: relative;
	}

	.shareImage {
		width: 655rpx;
		height: 90rpx;
		background: #81C042;
		border-radius: 45rpx;
		margin: 60rpx auto 0;
		line-height: 90rpx;
		text-align: center;
		font-size: 34rpx;
	}

	.hideCanvas {
		position: fixed;
		top: -99999upx;
		left: -99999upx;
		z-index: -99999;
	}

	.flex_row_c_c {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}

	.modalView {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		opacity: 0;
		outline: 0;
		transform: scale(1.2);
		perspective: 2500upx;
		background: rgba(0, 0, 0, 0.6);
		transition: all .3s ease-in-out;
		pointer-events: none;
		backface-visibility: hidden;
		z-index: 999;
	}

	.modalView.show {
		opacity: 1;
		transform: scale(1);
		pointer-events: auto;
	}

	.flex_column {
		display: flex;
		flex-direction: column;
	}

	.backgroundColor-white {
		background-color: white;
	}

	.border_radius_10px {
		border-radius: 10px;
	}

	.padding1vh {
		padding: 1vh;
	}

	.posterImage {
		width: 60vw;
	}

	.flex_row {
		display: flex;
		flex-direction: row;
	}

	.marginTop2vh {
		margin-top: 2vh;
	}


	.HealthReport {
		width: 750rpx;
		min-height: 1169rpx;
		background: #2EA7E0;
		border-radius: 40rpx 40rpx 0 0;
		margin: 20rpx auto 0;
		padding-bottom: 30rpx;
		.heavy-flex {
			display: flex;
			height: 160rpx;
			border-bottom: 1px solid #fff;

			.weight-view {
				width: 280rpx;
				padding-left: 20rpx;
				font-size: 30rpx;
				color: #fff;

				.weight-num {
					font-size: 60rpx;

					text {
						font-size: 30rpx;
					}
				}
			}
		}

		.titlename {
			font-size: 36rpx;
			color: #FFFFFF;
			height: 140rpx;
			line-height: 140rpx;
			padding: 0 20rpx;
			display: flex;

			.titlename-title,
			.titlename-time {
				width: 50%;
			}

			.titlename-time {
				font-size: 22rpx;
				text-align: right;
			}
		}
	}

	.reportItemList-body {
		.reportItemList {
			// height: 208rpx;
			text-align: center;

			.reportItemList-height {
				min-height: 80rpx;
				background: #fff;

				.view-progress {
					width: 706rpx;
					margin: 0 auto;
				}

				.view-levelNamesflex {
					width: 706rpx;
					margin: 0 auto;
					height: 60rpx;
					line-height: 60rpx;
					display: flex;
					justify-content: space-between;
					font-size: 24rpx;
				}

				.view-desc {
					width: 706rpx;
					margin: 0 auto;
					text-align: left;
					padding: 30rpx 0;
				}
			}
			.prbefoer0::before,.prbefoer1::before,.prbefoer2::before {
				content: '';
				position: absolute;
				left: 15%;
				top:-20rpx;
				width: 0;
				height: 0;
				border-left: 10rpx solid transparent;
				border-right: 10rpx solid transparent;
				border-bottom: 20rpx solid #fff;
			}
			.prbefoer1::before {
				left: 49.3%;
			}
			.prbefoer2::before {
				left: 82.3%;
			}
			
			.reportItemList-flex {
				display: flex;
				justify-content: left;
				border-bottom: 1px solid #fff;

				.reportItemList-item {
					width: 33.3%;
					height: 208rpx;
					color: #fff;
					padding-top: 30rpx;
					border-right: 1px solid #fff;
					font-size: 30rpx;

					.view-unit {
						font-size: 36rpx;

						text {
							font-size: 22rpx;
						}
					}

					.view-level {
						padding: 2rpx 20rpx;
						font-size: 22rpx;
						color: #81C042;
						background: #fff;
						display: inline-block;
						border-radius: 50rpx;
					}
				}
			}
		}
	}
</style>
